// [3447]-将元素分配给有约束条件的组
struct Solution;

//leetcode submit region begin(Prohibit modification and deletion)
impl Solution {
    pub fn assign_elements(groups: Vec<i32>, elements: Vec<i32>) -> Vec<i32> {
        let mut mem = Vec::new();
        let mut max_group = *groups.iter().max().unwrap() as usize;
        for _ in 0..=max_group {
            mem.push(-1i32);
        }

        for (j, &elem) in elements.iter().enumerate() {
            if elem > max_group as i32 || mem[elem as usize] >= 0 {
                continue;
            }
            let mut cur = elem as usize;
            while cur <= max_group {
                if mem[cur] < 0 {
                    mem[cur] = j as i32
                };
                cur += elem as usize;
            }
        }

        let mut groups = groups;
        for x in &mut groups {
            *x = mem[*x as usize];
        }
        groups
    }
}
//leetcode submit region end(Prohibit modification and deletion)

#[test]
fn main() {
    let groups = vec![8, 4, 3, 2, 4];
    let elements = vec![4, 2];
    assert_eq!(
        Solution::assign_elements(groups, elements),
        vec![0, 0, -1, 1, 0]
    );
    let groups = vec![2, 3, 5, 7];
    let elements = vec![5, 3, 3];
    assert_eq!(
        Solution::assign_elements(groups, elements),
        vec![-1, 1, 0, -1]
    );
    let groups = vec![10, 21, 30, 41];
    let elements = vec![2, 1];
    assert_eq!(
        Solution::assign_elements(groups, elements),
        vec![0, 1, 0, 1]
    );
}
